<template>
    <div style="background-color: #fff; ">
        <main-layout>
            <div style="width: 800px;">
                <div class="dttitle">{{details.stageName}}：</div>
                <el-form ref="ruleFormRef" :rules="rules" :model="formdata" label-width="80px" size="small">
                    <el-form-item label="农事事项" prop="stageTaskId">
                        <task-select v-if="details.stageTaskId" v-model="formdata.stageTaskId" :params="{stageId:details.stageId}"/>
                    </el-form-item>
                    <el-form-item label="农事位置" prop="plantLineLandIds">
                        <land-group-select ref="lgsRef" v-model="formdata.plantLineLandIds" width="100%" :multiple="true"/>
                    </el-form-item>
                    <el-form-item label="农事内容" prop="taskContent">
                        <el-input type="textarea" v-model="formdata.taskContent" :rows="12" placeholder="农事内容" show-word-limit maxlength="1000"/>
                    </el-form-item>
                    <el-form-item label="负责人" prop="fuzeUserIds">
                        <user-select v-model="formdata.fuzeUserIds" :multiple="true" placeholder="选择负责人" @change="getFuzeUser"/>
                    </el-form-item>
                    <el-form-item label="完成日期" prop="time">
                        <el-date-picker v-model="formdata.time" 
                            class="mydaterange" 
                            type="datetimerange" 
                            range-separator="-"
                            start-placeholder="开始日期"
                            end-placeholder="结束日期"
                            value-format="YYYY-MM-DD HH:mm:ss"/>
                    </el-form-item>

                    <el-form-item label="" prop="">
                        <el-button size="small" type="primary" @click="save">保 存</el-button>
                        <el-button size="small" @click="close">取 消</el-button>
                    </el-form-item>
                </el-form>
            </div>
        </main-layout>
    </div>
</template>
<script setup>
import { ref,onMounted,reactive } from 'vue';
import{useRouter,useRoute} from "vue-router"
import {getPlantLinelistDetail,editPlantLineItem} from '@/api/plant'
import mainLayout from '@/components/custom/mainLayout.vue'
import { message } from '@/utils/element'
import { emitter } from '@/utils/bus.js'
import taskSelect from '@/components/custom/taskSelect.vue'
import userSelect from '@/components/custom/userSelect.vue'
import landGroupSelect from '@/components/custom/landGroupSelect.vue'

const props = defineProps({
    show: {
        type: Boolean,
        default: false
    },
    title: String,
    editData: Object,
    type:Number // 操作类型：1为新增，2为编辑，3为查看
})
const emit = defineEmits(['update:show','success'])
const router = useRouter()
const route = useRouter()


const formdata = ref({})
const ruleFormRef = ref(null)
const farmRef = ref(null)
const plantLineId = ref('')
const details = ref({})
const getFuzeUserArr = ref([])


const rules = reactive({
    stageTaskId: [
        { required: true, message: '请选择农事事项', trigger: 'blur' },
        //{ min: 3, max: 50, message: 'Length should be 3 to 5', trigger: 'blur' },
    ],
    plantLineLandIds:[
        { required: true, message: '请选择地块', trigger: 'blur' },
    ],
    taskContent:[
        { required: true, message: '请输入农事内容', trigger: 'blur' },
    ],
    fuzeUserIds:[
        { required: true, message: '请选择负责人', trigger: 'blur' },
    ],
    time:[
        { required: true, message: '请输入完成日期', trigger: 'blur' },
    ],
})

onMounted(()=>{
    plantLineId.value = route.currentRoute.value.query.plantLineId
    get_plant_linelist_detail()
})

const getFuzeUser = (arr)=>{
    getFuzeUserArr.value = arr
    console.log("getFuzeUserArr:",getFuzeUserArr.value)
}

const get_plant_linelist_detail = async ()=>{
    const res = await getPlantLinelistDetail(plantLineId.value)
    details.value = res.data
    // 回填数据
    formdata.value.stageTaskId = details.value.stageTaskId
    formdata.value.taskContent = details.value.taskContent
    formdata.value.time = [details.value.taskStartTime,details.value.taskEndTime]

    formdata.value.fuzeUserIds = []
    details.value.fuzeUserList.forEach(item => {
        formdata.value.fuzeUserIds.push(item.fuzeUserId.toString())
    });

    formdata.value.plantLineLandIds = []
    details.value.lineLandRspList.forEach(item => {
        formdata.value.plantLineLandIds.push([parseInt(item.groupId),item.farmLandId])
    });
    
}

const save = async() => {
    await ruleFormRef.value.validate(async(valid, fields) => {
        if (valid) {
            // 负责人
            let fuzeUserList = []
            if(getFuzeUserArr.value.length){
                getFuzeUserArr.value.forEach(item =>{
                    fuzeUserList.push({fuzeRealName:item.meaning,fuzeUserId:item.code})
                }) 
            }else{
                details.value.fuzeUserList.forEach(item =>{
                    fuzeUserList.push({fuzeRealName:item.fuzeRealName,fuzeUserId:item.fuzeUserId})
                }) 
            }

            // 地块id数组
            let lineLandIdList = []
            formdata.value.plantLineLandIds.forEach(item =>{
                lineLandIdList.push(item[1])
            })

            let params = {
                fuzeUserList,// 负责人
                lineLandIdList, // 地块
                plantLineId:details.value.plantLineId,
                stageId:details.value.stageId,
                stageTaskId:formdata.value.stageTaskId,
                taskContent:formdata.value.taskContent,
                taskEndTime:formdata.value.time[1],
                taskStartTime:formdata.value.time[0],
            }
           // console.log("params:",params)

            const res= await editPlantLineItem(params)
    
            if(res.code ==0 || res.success){
                message('数据提交成功',2)
                close()
                emitter.emit('reload') // 刷新页面
            }else{
                message(res.message,3)
            }
        } 
    })
}

const setFarmData = (id)=>{
    farmRef.value.getTableData({companyId:id}) // 获取数据
}

const close = () => {
    emitter.emit('closeThisPage')
}
</script>
<style lang="scss" scoped>
    .dttitle{
        font-size: 14px;
        padding: 0 0 10px 0;
        border-bottom: 1px solid #ebeef5;
        margin: 0 0 20px 0;
        font-weight: bold;
    }
</style>
